<template>
  <div class="tw-libtable"
    :class="{xnoxborder: noXborder, [`x${_uid}`]: true, xnowrap:noWrap}">
    <div class="xpadding">
    <el-table
      :data="tableData"
      :key="keyLabel"
      header-row-class-name="xheader"
      border
      :cell-class-name="renderCellClass"
      :show-summary="showTotal"
      :summary-method="getSummaries"
      :span-method="arraySpanMethod"
      :max-height="maxHeights"
      style="width: 100%;"
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange">
      <el-table-column v-if="enableMulSelect"
        type="selection"
        :width="mulWidth">
      </el-table-column>
      <el-table-column
        v-for="(lv1Column, lv1Idx) in columns"
        :key="lv1Idx"
        :label="lv1Column.label"
        :prop="lv1Column.prop"
        :fixed="lv1Column.fixed"
        :align="lv1Column.align"
        :class-name="lv1Column.classname"
        :width="lv1Column.width"
        :sortable="lv1Column.sortable">

        <template v-if="lv1Column.children && lv1Column.children.length>0">
          <el-table-column
            v-for="(lv2Column, lv2Idx) in lv1Column.children"
            :key="lv2Idx"
            :label="lv2Column.label"
            :prop="lv2Column.prop"
            :align="lv2Column.align"
            :width="lv2Column.width"
            :sortable="lv2Column.sortable">
            <template v-if="lv2Column.children && lv2Column.children.length>0">
              <el-table-column
                v-for="(lv3Column, lv3Idx) in lv2Column.children"
                :key="lv3Idx"
                :label="lv3Column.label"
                :prop="lv3Column.prop"
                :align="lv3Column.align"
                :width="lv3Column.width"
                :sortable="lv3Column.sortable">
                <template slot-scope="scope">
                  <span v-if="enableHtmlTag" v-html="scope.row[lv3Column.prop]"></span>
                  <span v-else>{{ scope.row[lv3Column.prop] }}</span>
                </template>
              </el-table-column>
            </template>

            <template slot-scope="scope">
              <template v-if="enableHtmlTag">
                <span :style="{color: colors[lv1Idx]}" v-if="custColors" v-html="scope.row[lv2Column.prop]"></span>
                <span v-else v-html="scope.row[lv2Column.prop]"></span>
              </template>

              <template v-else>
                <span :style="{color: colors[lv1Idx]}" v-if="custColors">{{ scope.row[lv2Column.prop] }}</span>
                <span v-else>{{ scope.row[lv2Column.prop] }}</span>
              </template>
            </template>
          </el-table-column>
        </template>

        <template slot-scope="scope">
          <template v-if="enableHtmlTag">
            <template  v-if="custOperate && lv1Idx === columns.length - 1">
              <span :ref="'id_row_' + scope.$index" :id="'id_row_' + scope.$index" v-html="scope.row[lv1Column.prop]"></span>
            </template>
            <template v-else>
              <span :style="{color: colors[lv1Idx]}" v-if="custColors" v-html="scope.row[lv1Column.prop]"></span>
              <span v-else v-html="scope.row[lv1Column.prop]"></span>
            </template>
          </template>

          <template v-else>
            <span :style="{color: colors[lv1Idx]}" v-if="custColors">{{ scope.row[lv1Column.prop] }}</span>
            <span v-else>{{ scope.row[lv1Column.prop] }}</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column
        v-if="detailUrl"
        fixed="right"
        label="操作"
        :width="extent"
        :align="position">
        <template slot-scope="scope">
          <a :href="detailUrl+'?'+$ui.qs.stringify(scope.row)">
            <span>详情</span>
          </a>
        </template>
      </el-table-column>
      <!-- <el-table-column
        v-else-if="custOperate"
        fixed="right"
        label="操作"
        :width="extent"
        :align="position">
        <template slot-scope="scope">
          <div :ref="'id_tblr_' + scope.$index" :id="'id_tblr_' + scope.$index" v-html="tableData[scope.$index]"></div>
        </template>
      </el-table-column> -->
    </el-table>
    </div>
  </div>
</template>

<script>
import props from './props'
import { clearInterval } from 'timers'

export default {
  name: 'table',

  props,
  data () {
    return {
      timer: null,
      datatab: [],
      multipleSelection: []
    }
  },

  computed: {
    maxHeights () {
      if (this.maxHeight) {
        return this.maxHeight
      } else {
        return '100%'
      }
    },
    tableData () {
      if (this.datatab.length > 0) {
        if (Array.isArray(this.datatab[0])) {
          const result = []
          const props = []
          this.flatPropsFromData(this.columns, props)

          this.datatab.forEach(row => {
            const rowObj = {}

            row.forEach((item, idx) => {
              rowObj[props[idx]] = item
            })

            result.push(rowObj)
          })

          return result
        } else {
          return this.datatab
          // return this.data
        }
      } else {
        return []
      }
    },

    style () {
      return {
        fontSize: this.fontSize,
        bgColor: this.bgColor,
        borderColor: this.borderColor,
        cellPaddingY: this.cellPaddingY,
        cellPaddingX: this.cellPaddingX,
        headBg: this.headBg,
        headColor: this.headColor,
        headFontSize: this.headFontSize,
        extent: this.extent,
        position: this.position,
        custBorder: this.custBorder,
        enableScroll: this.enableScroll,
        nodataColor: this.nodataColor,
        intervalTime: this.intervalTime,
        enableScrollbar: this.enableScrollbar,
        headBdColor: this.headBdColor
      }
    }
  },

  methods: {
    flatPropsFromData (source, result) {
      for (const item of source) {
        if (item.children && item.children.length > 0) {
          this.flatPropsFromData(item.children, result)
        } else {
          result.push(item.prop)
        }
      }
    },

    setStyle () {
      let style = `
        ::root.tw-libtable .el-table {
          font-size: ${this.fontSize};
          background-color: ${this.bgColor};
          border-color: ${this.borderColor};
        }

        ::root.tw-libtable .el-table thead,
        ::root.tw-libtable .el-table thead th {
          font-size: ${this.headFontSize};
          color: ${this.headColor};
          background-color: ${this.headBg};
        }

        ::root.tw-libtable .el-table td,
        ::root.tw-libtable .el-table th.is-leaf {
          border-bottom-color: ${this.borderColor};
        }

        ::root.tw-libtable .el-table td,
        ::root.tw-libtable .el-table th {
          padding: ${this.cellPaddingY} 0;
        }

        ::root.tw-libtable .el-table--border,
        ::root.tw-libtable .el-table--group {
          border-color: ${this.borderColor};
        }

        ::root.tw-libtable .el-table--border::after,
        ::root.tw-libtable .el-table--group::after,
        ::root.tw-libtable .el-table::before {
          background-color: ${this.borderColor};
        }

        ::root.tw-libtable .el-table--border td,
        ::root.tw-libtable .el-table--border th,
        ::root.tw-libtable .el-table__body-wrapper
        ::root.tw-libtable .el-table--border.is-scrolling-left~.el-table__fixed {
          border-right-color: ${this.borderColor};
        }

        ::root.tw-libtable .el-table--border th,
        ::root.tw-libtable .el-table__fixed-right-patch {
          border-bottom-color: ${this.borderColor};
        }

        ::root.tw-libtable .el-table .cell,
        ::root.tw-libtable .el-table--border td:first-child .cell,
        ::root.tw-libtable .el-table--border th:first-child .cell {
          padding-left: ${this.cellPaddingX};
        }

        ::root.tw-libtable  .el-table th>.cell {
          padding: 0 ${this.cellPaddingX};
        }

        ::root.tw-libtable .el-table .cell {
          padding-right: ${this.cellPaddingX};
        }

        ::root.tw-libtable a {
          color: ${this.detailColor};
        }

        ::root.tw-libtable .el-table .el-table__empty-text {
          color: ${this.nodataColor};
        }

      `

      if (this.custBorder) {
        if (!this.enableScrollbar) {
          style += `
            ::-webkit-scrollbar {
              width: 10px;
            }

            ::-webkit-scrollbar-track {
              -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.1);
              border-radius: 10px;
            }

            ::-webkit-scrollbar-thumb {
              border-radius: 10px;
              background: rgba(0,82,217,0.5);
              -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.1);
            }

            ::-webkit-scrollbar-thumb:hover {
              border-radius: 10px;
              background: rgba(0,82,217,1);
              -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.1);
            }
          `
        }
        style += `
          ::root.tw-libtable .xpadding {
            border-radius: ${this.borderRadius};
            background-image: linear-gradient(to left, ${this.customcolors[0]}, ${this.customcolors[1]});
            padding: ${this.borderWidth};
          }
          ::root.tw-libtable .el-table {
            border-radius: ${this.borderRadius};
          }
          ::root.tw-libtable .el-table__header {
            background-image: linear-gradient(to left, ${this.customcolors[0]}, ${this.customcolors[1]});
            background-color: ${this.customcolors[0]}
          }

          ::root.tw-libtable .el-table tr {
            background-color: ${this.trBkgColor};
          }

          ::root.tw-libtable .el-table, ::root.tw-libtable .el-table__expanded-cell {
            background-color: ${this.customcolors[2]}
          }

          ::root.tw-libtable .el-table__fixed-right::before, ::root.tw-libtable .el-table__fixed::before {
            background-color: ${this.trBkgColor};
          }

          ::root.tw-libtable .el-table__footer-wrapper tbody td, .el-table__header-wrapper tbody td {
            background-color: ${this.trBkgColor};
          }
          ::root.tw-libtable .el-table th, .tw-libtable .el-table thead.is-group th, .tw-libtable .el-table tr {
            background-color: ${this.trBkgColor};
          }

          ::root.tw-libtable .el-table__footer-wrapper td {
            color: ${this.headColor};
            border-top: 1px solid ${this.borderColor};
          }

          ::root.tw-libtable .el-table--striped .el-table__body tr.el-table__row--striped.current-row td, ::root.tw-libtable .el-table__body tr.current-row>td, ::root.tw-libtable .el-table__body tr.hover-row.current-row>td, ::root.tw-libtable .el-table__body tr.hover-row.el-table__row--striped.current-row>td, ::root.tw-libtable .el-table__body tr.hover-row.el-table__row--striped>td, ::root.tw-libtable .el-table__body tr.hover-row>td {
            background-color: ${this.hoverBkgColor};
          }
          ::root.tw-libtable .el-table tbody tr:hover > td {
            background-color: ${this.hoverBkgColor};
            color: ${this.hoverColor};
          }

        `
      }

      if (this.headBorder) {
        if (this.noXborder) {
          style += `
            ::root.tw-libtable .el-table thead th.xbdleft {
              border-left: 1px solid ${this.headBdColor};
            }
            ::root.tw-libtable .el-table thead th.xbdright {
              border-right: 1px solid ${this.headBdColor};
            }
          `
        } else {
          style += `
            ::root.tw-libtable .el-table thead th {
              border-right: 1px solid ${this.headBdColor};
            }
          `
        }
      }

      if (this.headBdColor) {
        style += `
          ::root.tw-libtable .el-table thead th {
            border-color: ${this.headBdColor};
          }
          ::root.tw-libtable .el-table thead th.is-leaf {
            border-bottom-color: ${this.headBdColor};
          }
        `
      }

      if (this.funcStyle !== '' && typeof this.funcStyle === 'function') {
        let custyle = this.funcStyle(this)
        style += custyle
      }
      // if (true) {
      //   style += `
      //     ::root.tw-libtable .el-table thead.is-group tr:first-of-type th:first-of-type:before {
      //       content: '日期';
      //       text-align: center;
      //       position: absolute;
      //       width: 120px;
      //       height: 1px;
      //       bottom: 30px;
      //       right: 0;
      //     }

      //     ::root.tw-libtable .el-table thead.is-group tr:first-of-type th:first-of-type:after {
      //       content: '配送新增';
      //       text-align: center;
      //       position: absolute;
      //       width: 120px;
      //       top: 10px;
      //       left: 0;
      //     }

      //     ::root.tw-libtable .el-table thead.is-group tr:first-of-type th:first-of-type .cell {
      //       position: absolute;
      //       top: 0;
      //       left: 0;
      //       width: 120px;
      //       height: 1px;
      //       background-color: #000;
      //       display: block;
      //       text-align: center;
      //       transform: rotate(45deg);
      //       transform-origin: top left;
      //       -ms-transform: rotate(45deg);
      //       -ms-transform-origin: top left;
      //       -webkit-transform: rotate(45deg);
      //       -webkit-transform-origin: top left;
      //     }
      //   `
      // }

      this.addStyle(style)
    },

    addStyle (style) {
      this.$el.classList.add(`x${this._uid}`)
      const styleEl = document.getElementById(this._uid) || document.createElement('style')
      styleEl.id = this._uid
      styleEl.innerText = style.replace(/::root/gm, `.x${this._uid}`).replace(/\n/gm, '')

      document.head.appendChild(styleEl)
    },

    sortChange (sortData) {
      this.$emit('sortchange', sortData)
    },

    setTabData () {
      const vm = this
      if (vm.enableScroll) {
        this.datatab = []
        this.data.forEach(item => {
          const a = item
          this.datatab.push(a)
        })
        if (vm.timer) {
          window.clearInterval(vm.timer)
          vm.timer = null
        }
        vm.timer = setInterval(() => {
          vm.datatab.push(vm.datatab[0])
          vm.datatab.shift()
        }, parseInt(this.intervalTime))
      } else {
        this.datatab = this.data
      }
      if (this.custOperate) {
        this.$nextTick(() => {
          this.custOperateFunc()
        })
      }
    },
    getSummaries (param) {
      const vm = this
      if (vm.funcSum !== '' && typeof vm.funcSum === 'function') {
        vm.funcSum(param)
      } else {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
          } else {
            sums[index] = ''
          }
        })

        return sums
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.$emit('selectdata', val)
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      let rdata = []
      if (this.spanMethodFn !== '' && typeof this.spanMethodFn === 'function') {
        rdata = this.spanMethodFn({ row, column, rowIndex, columnIndex }, this)
        if (rdata.length > 0) {
          return rdata
        }
      }
    },

    renderCellClass ({ row, column, rowIndex, columnIndex }) {
      if (this.funcCellStyle !== '' && typeof this.funcCellStyle === 'function') {
        return this.funcCellStyle({ row, column, rowIndex, columnIndex }, this)
      }
    },
    custOperateFunc () {
      if (this.custOperateFn !== '' && typeof this.custOperateFn === 'function') {
        this.custOperateFn(this)
      }
      this.$emit('selectbutton', true)
    },
    testFunc () {
      let vm = this
      console.log('ddd', this.$refs)
      for (let i=0; i< vm.data.length; i++) {
        console.log('fff', `id_row_` + i)
        console.log(this.$refs.[`id_row_` + i][1].childNodes[0])
        for (let j = 0; j < this.$refs.[`id_row_` + i][1].childNodes.length; j++) {
          this.$refs.[`id_row_` + i][1].childNodes[j].addEventListener('click', vm.test)
        }
      }
    },
    test () {
      console.log('lll')
      // 函数写法参考以下
      // console.log('dddss', this.$root.dialogVisible)
      // let root = this.$root

      // for (let i=0; i< vm.data.length; i++) {
      //   console.log('fff', `id_row_` + i)
      //   let key = 'id_row_' + i
      //   let length = this.$refs[key][1].childNodes.length
      //   for (let j = 0; j < length; j++) {
      //     this.$refs[key][1].childNodes[j].addEventListener('click', function () {
      //       root.dialogVisible = true
      //     })
      //   }
      //   console.log(this.$refs[key][1].childNodes.length)
      // }

    }
  },

  mounted () {
    this.setStyle()
    this.setTabData()
  },

  watch: {
    style: {
      deep: true,
      handler () {
        this.setStyle()
      }
    },
    data: {
      deep: true,
      handler () {
        this.setTabData()
      }
    }
  },

  beforeDestroy () {
    if (this.timer) {
      window.clearInterval(this.timer)
      this.timer = null
    }
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
